﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Lucene.Net.Index;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using System.IO;
using Lucene.Net.Store;
using Lucene.Net.Search;
using Lucene.Net.QueryParsers;
using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Analysis;

namespace VHWebStudy.App_Code
{
    public class LuceneKit
    {
        public static bool AddIndex(string arcId,string arcName)
        {
            bool result = false;
            string indexPath = "E://IndexPath";
            string segPath = Path.Combine(indexPath,"1");
            //加入索引
            IndexWriter writer=null;
            FSDirectory directory = null;
            StandardAnalyzer analyzer = null;
            try
            {
                directory = FSDirectory.Open(new DirectoryInfo(segPath), new NativeFSLockFactory());
                //IndexReader:对索引库进行读取的类
                bool indexFileExist = IndexReader.IndexExists(directory); //是否存在索引库文件夹以及索引库特征文件
                if (indexFileExist)
                {
                    //如果索引目录被锁定（比如索引过程中程序异常退出或另一进程在操作索引库），则解锁
                    //Q:存在问题 如果一个用户正在对索引库写操作 此时是上锁的 而另一个用户过来操作时 将锁解开了 于是产生冲突 --解决方法后续
                    if (IndexWriter.IsLocked(directory))
                    {
                        IndexWriter.Unlock(directory);
                    }
                }
                analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
                if (indexFileExist)
                {                    
                    writer = new IndexWriter(directory,analyzer , false, IndexWriter.MaxFieldLength.UNLIMITED);
                }
                else
                {
                    writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
                }


                

                Document doc = new Document();
                //Field.Index.NOT_ANALYZED 不分词索引
                //Field.Index.ANALYZED 分词索引
                doc.Add(new Field("arcId", arcId, Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.Add(new Field("arcName", arcName, Field.Store.YES, Field.Index.NOT_ANALYZED));
                writer.AddDocument(doc);
                writer.Optimize();
                result = true;
            }
            catch (Exception e)
            {

            }
            finally
            { 
                if (analyzer != null)  
                    analyzer.Close();
                if (writer != null)
                    writer.Dispose();
                if (directory != null)
                    directory.Dispose(); 
            }
            return result;
        }

        public static void DeleteIndex(string arcId)
        {
            bool result = false;
            string indexPath = "E://IndexPath";
            string segPath = Path.Combine(indexPath,"1");
            //加入索引
            IndexWriter writer=null;
            FSDirectory directory = null;
            StandardAnalyzer analyzer = null;
            try
            {
                directory = FSDirectory.Open(new DirectoryInfo(segPath), new NativeFSLockFactory());
                //IndexReader:对索引库进行读取的类
                bool indexFileExist = IndexReader.IndexExists(directory); //是否存在索引库文件夹以及索引库特征文件
                if (indexFileExist)
                {
                    //如果索引目录被锁定（比如索引过程中程序异常退出或另一进程在操作索引库），则解锁
                    //Q:存在问题 如果一个用户正在对索引库写操作 此时是上锁的 而另一个用户过来操作时 将锁解开了 于是产生冲突 --解决方法后续
                    if (IndexWriter.IsLocked(directory))
                    {
                        IndexWriter.Unlock(directory);
                    }
                }
                analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
                if (indexFileExist)
                {
                    writer = new IndexWriter(directory, analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
                    Query query = new TermQuery(new Term("arcId", arcId));
                    writer.DeleteDocuments(query);
                }
            }
            catch (Exception e)
            {

            }
            finally
            {
                if (analyzer != null)
                    analyzer.Close();
                if (writer != null)
                    writer.Dispose();
                if (directory != null)
                    directory.Dispose(); 
            }
        }

        public static void UpdateIndex(string arcId,string arcName)
        {
            bool result = false;
            string indexPath = "E://IndexPath";
            string segPath = Path.Combine(indexPath, "1");
            //加入索引
            IndexWriter writer = null;
            FSDirectory directory = null;
            StandardAnalyzer analyzer = null;
            try
            {
                directory = FSDirectory.Open(new DirectoryInfo(segPath), new NativeFSLockFactory());
                //IndexReader:对索引库进行读取的类
                bool indexFileExist = IndexReader.IndexExists(directory); //是否存在索引库文件夹以及索引库特征文件
                if (indexFileExist)
                {
                    //如果索引目录被锁定（比如索引过程中程序异常退出或另一进程在操作索引库），则解锁
                    //Q:存在问题 如果一个用户正在对索引库写操作 此时是上锁的 而另一个用户过来操作时 将锁解开了 于是产生冲突 --解决方法后续
                    if (IndexWriter.IsLocked(directory))
                    {
                        IndexWriter.Unlock(directory);
                    }
                }
                analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
                if (indexFileExist)
                {
                    writer = new IndexWriter(directory, analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
                    Term t = new Term("arcId", arcId);
                    Document d=new Document();
                    d.Add(new Field("arcId", arcId, Field.Store.YES, Field.Index.ANALYZED));
                    d.Add(new Field("arcName",arcName,Field.Store.YES,Field.Index.ANALYZED));
                    writer.UpdateDocument(t,d);
                    writer.Optimize();
                }
            }
            catch (Exception e)
            {

            }
            finally
            {
                if (analyzer != null)
                    analyzer.Close();
                if (writer != null)
                    writer.Dispose();
                if (directory != null)
                    directory.Dispose();
            }
        }

        public static List<Archive> IndexSearch(string arcId, string arcName)
        {
            string indexPath = "E://IndexPath";
            string segPath = Path.Combine(indexPath, "1");
            FSDirectory directory = null;
            StandardAnalyzer analyzer = null;
            IndexSearcher searcher = null;
            List<Archive> list= new List<Archive>();
            Lucene.Net.Util.Version ver = Lucene.Net.Util.Version.LUCENE_30;
            try
            {
                directory = FSDirectory.Open(new DirectoryInfo(segPath), new NativeFSLockFactory());
                analyzer = new StandardAnalyzer(ver);//StandardAnalyzer只支持英文的空格分词
                //Analyzer analyzer2 = new PanGuAnalyzer();//使用盘古分词
                searcher = new IndexSearcher(directory, true);

                //多字段查询
                string[] fields = { "arcId" };                
                MultiFieldQueryParser parser = new MultiFieldQueryParser(ver, fields, analyzer);
                Query query = parser.Parse(arcId);

                //组合查询
                BooleanQuery booleanQuery = new BooleanQuery();
                booleanQuery.Add(query, Occur.MUST); //MUST与，SHOULD或，MUST_NOT非

                //Query query1 = new QueryParser(ver, "arcId", analyzer).Parse(arcId);

                //TermQuery只能查询不分词的索引(Field.Index.NOT_ANALYZED)  
                Query query2 = new TermQuery(new Term("arcName", arcName));

                //前缀查询
                Query query3 = new PrefixQuery(new Term("arcName",arcName));
                   
                //日期范围查询
                TermRangeQuery query4 = new TermRangeQuery("time", "2017-1-1", "2017-10-1", true, true);

                //模糊查询
                Term t = new Term("arcName", "*" + arcName + "*");
                WildcardQuery query5 = new WildcardQuery(t);
                
                TopDocs ts = searcher.Search(query, null, 100);//执行搜索，获取查询结果集对象
                int recCount = ts.TotalHits;//获取命中的文档个数 
                ScoreDoc[] hits = ts.ScoreDocs;//获取命中的文档信息对象

                foreach (var item in hits)
                {
                    list.Add(new Archive()
                    {
                        arcId = searcher.Doc(item.Doc).Get("arcId"),
                        arcName = searcher.Doc(item.Doc).Get("arcName"),
                    });
                }  
            }
            catch (Exception e)
            {
                
            }
            finally
            {
                if (analyzer != null)
                    analyzer.Close();
                if (searcher != null)
                    searcher.Dispose();
                if (directory != null)
                    directory.Dispose(); 
            }
            return list;
        }
    }

    public class Archive
    {
        public string arcId { get; set; }
        public string arcName { get; set; }
    }
}